package com.example.itshome.manager;

import android.app.Activity;
import android.content.Context;
import com.example.itshome.entity.UserEntity;
import com.example.itshome.network.AbstractNetworkRequest;
import com.example.itshome.network.AbstractRecycleVIewGetRequest;
import com.example.itshome.network.InitUserInfoRequest;
import com.example.itshome.util.SharePreferencesUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserInfoManager {
    private static volatile UserInfoManager instance;
    private UserEntity user;
    private String tokenRequest;
    private String tokenRefresh;
    private UserInfoManager(){}
    private Set<OnUpdateUserRunner> runners;

    public String getTokenRequest() {
        return tokenRequest;
    }

    public String getTokenRefresh() {
        return tokenRefresh;
    }

    public UserInfoManager setTokenRequest(String tokenRequest) {
        this.tokenRequest = tokenRequest;
        return this;
    }

    public UserInfoManager setTokenRefresh(String tokenRefresh) {
        this.tokenRefresh = tokenRefresh;
        return this;
    }

    public void addRunners(OnUpdateUserRunner runner){
        runners.add(runner);
    }

    public static UserInfoManager getInstance()
    {
        if(instance==null){
            synchronized (UserInfoManager.class){
                if(instance==null){
                    instance=new UserInfoManager();
                    instance.user=new UserEntity();
                    instance.runners=new HashSet<>();
                }
            }
        }
        return instance;
    }

    public void initUser(Activity activity){
        AbstractNetworkRequest request=new InitUserInfoRequest(activity)
                .setEntity(user);
        request.start();

    }

    public void initTokenAndUsername(Context context){
        SharePreferencesUtil util=new SharePreferencesUtil(context,SharePreferencesUtil.USERFile);
        tokenRequest= util.getString("tokenRequest");
        tokenRefresh= util.getString("tokenRefresh");
        user.setUsername(util.getString("username"));
    }





    public void callRunner(){
        for (OnUpdateUserRunner runner:runners){
            runner.onInfoUpdate();
        }
    }

    public UserEntity getUser() {
        return user;
    }

    public interface OnUpdateUserRunner{
        void onInfoUpdate();
    }

}
